package com.zhw.intercept;

import com.alibaba.fastjson.JSONObject;
import com.zhw.Util.JwtUtils;
import com.zhw.pojo.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j
public class loginCheckIntercept implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        目标资源执行之前执行此方法，false为拦截，true为放行
        log.info("preHandle执行");
/*//         获取请求url
        String url = request.getRequestURI();*/

//         获取请求头内的token令牌
        String jwt = request.getHeader("token");

//         判断令牌是否存在，不存在则拦截
        if (!StringUtils.hasLength(jwt)){
            log.info("令牌不存在，拦截");
            Result error = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(error);
            response.getWriter().write(jsonString);
            return false;
        }

//         判断令牌是否真实有效，不有效则拦截
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("非法令牌");
            Result error = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(error);
            response.getWriter().write(jsonString);
            return false;
        }


//        筛选过后的判定用户已登录，所以执行放行操作
        log.info("令牌有效，放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//          目标资源执行之后执行此方法
        log.info("postHandle执行");


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//            整个视图渲染之后执行此方法，最后执行的方法
        log.info("afterCompletion执行");
    }
}
